#coding=utf-8
# 针对mnist数据集的 采用TF2.0 的三层神经网络手动构建
# 进行绘图

import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics

### 数据加载 与处理
(x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()  # 首次运行要等待下载
# 数据保存在C:\Users\Carson\.keras\datasets

print(x_train.shape)
print(y_train.shape)

x_train = x_train / 255.0
x_test = x_test / 255.0
x_train = x_train.reshape(x_train.shape[0], -1).astype(np.float32)  # 转成60000*784的矩阵数据
x_test = x_test.reshape(x_test.shape[0], -1).astype(np.float32)  # 转成10000*784的矩阵数据

y_train = tf.one_hot(y_train, depth=10)
y_test = tf.one_hot(y_test, depth=10)
# print(x_test.shape)
test_size, num_feas = x_test.shape
labels = 10

### 载入模型 ##############
model = keras.models.load_model('.\data\course8_1_model.h5', compile=True)

model.summary()

#### 评估训练集与测试集 ##########################################
print(model.evaluate(x_train, y_train, batch_size=3000))
# print(model.evaluate(x_test, y_test, batch_size = 3000))

y_pred = model.predict(x_test)
# acc = metrics.SparseCategoricalAccuracy()(y_test, y_pred)
acc = metrics.categorical_accuracy(y_test, y_pred)
print(acc)

##### 绘制混淆矩阵与 report ###############################
print('y_test:', y_test.shape, y_test.dtype)
print('y_pred', y_pred.shape, y_pred.dtype)

y_test = np.argmax(y_test, axis=1)  # 获得最大的概率的位置 作为分类标签
y_pred = np.argmax(y_pred, axis=1)  # 获得最大的概率的位置 作为分类标签
print('y_', y_pred.shape, y_pred.dtype)

from sklearn.metrics import classification_report, confusion_matrix

report = classification_report(y_test, y_pred)  ## 分类报告
print('输出分类报告：\n', report)
cm = confusion_matrix(y_test, y_pred)  # 混淆矩阵
print('混淆矩阵：\n', cm)


########## 画出混淆矩阵  ################################
def plotConfusionMatrix(cm, lalels, fig=1):
    # plt.figure(fig)
    lens = len(lalels)
    classes = [str(i) for i in range(lens)]
    plt.matshow(cm, interpolation='nearest', cmap=plt.cm.Blues)

    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes)
    plt.yticks(tick_marks, classes)
    for x in range(len(cm)):
        for y in range(len(cm)):
            plt.annotate(cm[x, y], xy=(x, y), horizontalalignment='center', verticalalignment='center')

    plt.grid(True, which='minor', linestyle='-')
    print('Confusion matrix, without normalization')

plotConfusionMatrix(cm=cm, lalels=range(10))
#### 错分的样例图片#######################################################
numForPaint = 16
ins = y_test == y_pred
diff_index = np.where(ins == False)[0]
plt.figure(0)

for i in range(numForPaint):
    j = diff_index[i]
    img = x_test[j].reshape(28, 28) * 255
    plt.subplot(2, 8, i + 1, xticks=[], yticks=[])
    plt.imshow(img, cmap='Greys')
    plt.title(f'{y_test[j]}--> {y_pred[j]}')




plt.show()
print('done')
